import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from sklearn.model_selection import  train_test_split
from sklearn.metrics import explained_variance_score,mean_absolute_error,mean_squared_error,median_absolute_error,r2_score
plt.rcParams['font.sans-serif']='SimHei'
plt.rcParams['axes.unicode_minus'] = False
data = pd.read_csv(r"E:\机器学习\水质数据建模预测\data\去噪后的数据.csv", sep=',',encoding='gbk')
y = data.iloc[:,1]
x = data.iloc[:,[564,612, 510,110,221,436]]
train_x,test_x,train_y,test_y = train_test_split(x,y,test_size=0.3,random_state=12)
model = LinearRegression().fit(train_x,train_y)
# 查看训练集的拟合效果
train_score = model.score(train_x,train_y)
# 预测值
y_pred = model.predict(test_x)
# 产看测试集的训练效果
test_score = model.score(test_x,test_y)
print(y_pred)
print("训练集效果：",train_score)
print("测试集效果",test_score)
print("平均绝对误差：",mean_absolute_error(test_y,y_pred))
print("均方误差：",mean_squared_error(test_y,y_pred))
print("中值绝对误差：",median_absolute_error(test_y,y_pred))
print("可解释方差值：",explained_variance_score(test_y,y_pred))
print("R2值：",r2_score(test_y,y_pred))
# 图形展示
plt.figure(figsize=(10,8))
plt.plot(range(1,len(test_y)+1),test_y,"r")
plt.plot(range(1,len(y_pred)+1),y_pred,"b")
plt.legend(["test_y","y_pred"])
plt.title('pso_linsear')
plt.show()